<template>
  <div>
    <hot-table
      ref="hotTable"
      :data="templateData"
      :settings="hotSettings"
      class="margin-top text-sm"
    ></hot-table>
    <div v-loading.fullscreen.lock="fullscreenLoading"></div>
  </div>
</template>

<script>
import { clone } from "@/utils/clone";
import { getFindKey, parseTime } from "@/utils";
import { HotTable } from "@handsontable/vue";
import Handsontable from "handsontable";
import { ajax } from "@/store/yg/common/utils";
import axios from "axios";
import { m } from "@/store/yg/common/local";
import * as constant from "@/store/yg/common/constant";
import "handsontable/languages/zh-CN";
import "handsontable/dist/handsontable.full.css";
import globalData from "@/utils/config";
// import { log } from "console";
export default {
  components: {
    HotTable
  },
  props: {
    Constatvariable: {
      type: Object,
      default: function() {
        return {};
      }
    },
    templateOptUser: {
      type: String,
      default: ""
    },

    templateData: {
      type: Array,
      default: function(params) {
        return [{}];
      }
    },
    receveToPay: {
      type: Array,
      default: function(params) {
        return [{}];
      }
    },
    payToReceve: {
      type: Array,
      default: function(params) {
        return [{}];
      }
    },
    templateDelReceveIds: {
      type: Array,
      default: function(params) {
        return [];
      }
    },
    templateDelPayIds: {
      type: Array,
      default: function(params) {
        return [];
      }
    },
    templateOptions: {
      type: Object,
      default: function(params) {
        return {};
      }
    }
  },
  data() {
    return {
      autoHeight: "auto",
      fullscreenLoading: false,
      headerList: [
        "公司",
        "费用名称",
        "类型",
        "数量",
        "单价",
        "币种",
        "总额",
        "余额",
        "账单类型",
        "录入人",
        "修改人",
        "备注",
        "费用日期",
        "操作"
      ],
      columns: [
        {
          data: "serCusId", // 公司
          width: 200,
          // type: "dropdown",
          // source: this.templateOptions.serviceOptions
          type: "autocomplete",
          source: async (query, process) => {
            const s = this.templateOptions.serviceOptions.filter(
              x => x.indexOf(query) > -1
            );
            process(s);
          }
        },
        {
          data: "costName", // 费用名称
          width: 200,
          type: "autocomplete",
          source: async (query, process) => {
            const s = this.templateOptions.configPayNameOptions.filter(
              x => x.indexOf(query) > -1
            );
            process(s);
          }
        },
        {
          data: "costNameType", // 类型
          width: 80,
          readOnly: true,
          type: "text" //
        },

        {
          data: "count", //数量
          width: 60,
          type: "numeric",

          validator: function(value, callback) {
            let val = value.toString();
            if (val.indexOf("-") > -1) {
              val = val.slice(1);
            }
            if (val.length <= 5) {
              callback(true);
            } else {
              callback(false);
            }
          }
        },
        {
          data: "unitPrice", //单价
          width: 60,
          type: "numeric",

          validator: function(value, callback) {
            let val = value.toString();
            console.log("val :>> ", val);
            if (val.indexOf("-") > -1) {
              val = val.slice(1);
            }

            val = val.slice(0, val.indexOf("."));
            console.log("val :>> ", val);
            if (val.length <= 5) {
              callback(true);
            } else {
              callback(false);
            }
          }
        },
        {
          data: "currency", // 币种
          width: 60,
          type: "dropdown",
          source: async (query, process) => {
            const s = this.templateOptions.currencyOptions.filter(
              x => x && x.indexOf(query) > -1
            );
            process(s);
          }
        },
        {
          data: "totalCost", //总额
          width: 60,
          type: "numeric",
          readOnly: true,
          numericFormat: {
            pattern: "0.00"
          }
        },
        {
          data: "remain", // 余额
          width: 60,
          type: "numeric",
          readOnly: true,
          numericFormat: {
            pattern: "0.00"
          }
        },
        {
          data: "billType", //账单类型
          width: 80,
          type: "dropdown",
          source: this.templateOptions.options
        },

        {
          data: "inputUser", // 录入人
          width: 80,
          readOnly: true,
          type: "text"
        },
        {
          data: "lastOperator", //修改人
          readOnly: true,
          width: 80,
          type: "text"
        },
        {
          data: "remark", //备注
          width: 200,
          type: "text"
        },

        {
          data: "accountDate",
          width: 100,
          type: "date",
          dateFormat: "YYYY-MM-DD"
        },
        {
          readOnly: true,
          width: 100,
          renderer: this.coverRenderer
        }
      ]
    };
  },
  computed: {
    hotSettings() {
      return {
        stretchH: "all", // 所有列宽小于表宽时,填充满整个表 all（所有列填充）/last（最后一列）/none(不填充)
        licenseKey: globalData.licensekey,
        // 定义表结构
        colHeaders: this.headerList,
        width: "100%",
        height: this.autoHeight,
        columns: this.columns,
        language: "zh-CN",
        contextMenu: ["row_above", "row_below", "remove_row", "alignment"], // 开启右键菜单
        beforeRemoveRow: (index, amount, physicalRows, source) => {
          if (this.templateData.length === 1) {
            this.templateData.push({});
          }
        },
        beforeChange: (changes, source) => {
          //数据改变时触发此方法 捕捉数据更改
          if (source && "edit" == source) {
            const [row, prop, oldValue, newValue] = changes[0];

            if (prop) {
              if (prop == "count") {
                // 修改数量
                if (this.templateData[row].unitPrice < 0 && newValue < 0) {
                  this.$notify.error({
                    position: "bottom-right",
                    message: "不能数量与单价两个都是负数"
                  });
                  changes.length = 0;
                  return;
                }

                this.changeCount(row, newValue);
              } else if (prop == "unitPrice") {
                console.log("1111 :>> ", 1111);
                // if (
                //   this.templateType === "receivable" &&
                //   this.oldData.length > 0 &&
                //   this.oldData[row] &&
                //   this.oldData[row].costName === "运费" &&
                //   this.templateData[row].costName === "运费" &&
                //   newValue < this.oldData[row].unitPrice
                // ) {
                //   this.$notify.error({
                //     position: "bottom-right",
                //     message: "修改后的运费比原数据小"
                //   });
                //   changes.length = 0;
                //   return;
                // }
                // console.log("222 :>> ", 222);
                // 修改单价
                if (this.templateData[row].count < 0 && newValue < 0) {
                  this.$notify.error({
                    position: "bottom-right",
                    message: "不能数量与单价两个都是负数"
                  });
                  changes.length = 0;
                  return;
                }
                this.changeUnitPrice(row, newValue);
              } else if (prop == "costName") {
                // 修改费用名称
                this.changePayName(row, newValue);
              } else if (prop == "configPayTypec") {
                // 判断是否可以修改C类
                if (this.templateData[row].costNameType !== "C") {
                  this.$notify({
                    type: "warning",
                    message: "仅仅当费用名称为C类的时候需要录入",
                    position: "bottom-right"
                  });
                  changes.length = 0;
                  return;
                }
              }
            }
          }
        },

        afterChange: (changes, source) => {
          //数据改变时触发此方法 捕捉数据更改
          if (!changes) return;
          // 解构赋值
          const [row, prop, oldValue, newValue] = changes[0];
          console.log("prop :>> ", prop);
          // const t = this.templateData[row];
          // if (newValue && prop === "serCusId") {
          //   const id = getFindKey(
          //     newValue,
          //     this.templateOptions.serviceCompanyMap
          //   );

          // }
          // if (newValue && prop === "costName") {
          //   const id = getFindKey(
          //     newValue,
          //     this.templateOptions.configPayNameMap
          //   );

          //   // console.log("id :>> ", id);
          //   this.$delete(t, "costName");
          //   this.$set(t, "costName", Number(id));
          // }
          // if (newValue && prop === "billType") {
          //   let id = 0;
          //   if (newValue === "目") {
          //     id = 1;
          //   }
          //   this.$delete(t, "billType");
          //   this.$set(t, "billType", id);
          // }
          // if (
          //   (newValue && prop === "count" && t.unitPrice) ||
          //   (prop === "unitPrice" && t.count)
          // ) {
          //   this.changeCount();
          // }
        }
      };
    }
  },
  watch: {
    templateData(newValue, oldValue) {
      var length = this.templateData.length;
      console.log("监控 所有的数据长度", length);
      if (length < 3) {
        this.autoHeight = "250px";
      } else {
        this.autoHeight = "auto";
      }
    }
  },
  methods: {
    rowReadonly(row, col, prop) {
      var cellProperties = {};
      if (this.templateData[row].readOnly) {
        cellProperties.readOnly = true;
      }
      return cellProperties;
    },
    changePayName(index, val) {
      const payTypeVal = getFindKey(val, this.templateOptions.configPayNameMap);
      const payType = this.templateOptions.configPayTypeMap[payTypeVal];
      this.$set(this.templateData[index], "costNameType", payType);
    },
    changeCount(index, val) {
      const target = this.templateData[index];
      const totalCost = (target.unitPrice * 100 * val) / 100;

      this.$set(this.templateData[index], "totalCost", totalCost.toFixed(2));
      this.$set(this.templateData[index], "remain", totalCost.toFixed(2));
    },
    changeUnitPrice(index, val) {
      const target = this.templateData[index];
      const totalCost = (val * 100 * target.count) / 100;
      this.$set(this.templateData[index], "totalCost", totalCost.toFixed(2));
      this.$set(this.templateData[index], "remain", totalCost.toFixed(2));
    },

    coverRenderer(instance, td, row, col, prop, value, cellProperties) {
      td.innerHTML = ``; // 清空单元格子集

      let btnCopy = document.createElement("i");
      let btn2 = document.createElement("i");
      btnCopy.onclick = params => {
        console.log("2 :>> ", 2);
        this.onCopy(row);
      };
      btnCopy.setAttribute(
        "class",
        "el-icon-circle-plus-outline margin-right-sm text-green"
      );

      td.appendChild(btnCopy); //添加按钮到单元格

      if (!this.templateData[row].readOnly) {
        let btnDel = document.createElement("i");

        btnDel.setAttribute(
          "class",
          "el-icon-remove-outline margin-right-sm text-red"
        );
        btnDel.setAttribute("v-loading.fullscreen.lock", "fullscreenLoading");
        btnDel.onclick = params => {
          console.log("this :>> ", this);
          this.onDel(row);
        };
        if (this.templateType === "receivable") {
          if (this.Constatvariable["status"] != 999) {
            td.appendChild(btnDel); //添加按钮到单元格
          }
        } else {
          td.appendChild(btnDel); //添加按钮到单元格
        }
      }

      return td;
    },
    onDel(row) {
      if (this.templateData.length > 0) {
        const data = clone(this.templateData[row]);

        if (data.id) {
          this.templateDelPayIds.push(data.id);
        }

        this.templateData.splice(row, 1);
      }
    },
    onCopy(row) {
      const data = this.templateData[row];
      this.templateData.splice(row + 1, 0, {
        serCusId: data.serCusId,
        costName: data.costName,
        costNameType: data.costNameType,
        inputUser: this.templateOptUser,
        lastOperator: "",

        unitPrice: "",
        count: "",
        currency: data.currency,
        totalCost: "",
        remain: "",
        billType: data.billType,
        amoebaSubjectId: "",
        accountDate: parseTime(new Date().toLocaleDateString(), "{y}-{m}-{d}"),
        remark: ""
      });
    },

    checkRule(i) {
      if (!i.serCusId) {
        this.$message.error("请填写公司名");
        return false;
      } else if (!i.costName) {
        this.$message.error("请填写费用名称");
        return false;
      } else if (i.configPayTypec === "C3" && !i.responsibleId) {
        this.$message.error("请填写责任人");
        return false;
      } else if (!i.count) {
        this.$message.error("请填写数量");
        return false;
      } else if (!i.currency) {
        this.$message.error("请填写币种");
        return false;
      } else if (!i.unitPrice) {
        this.$message.error("请填写单价");
        return false;
      } else if (!i.billType) {
        this.$message.error("请填写账单类型");
        return false;
      }

      return true;
    }
  }
};
</script>

<style></style>
